package com.zsy.petshop_01.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zsy.petshop_01.dao.mapper.ProductMapper;
import com.zsy.petshop_01.model.entity.Product;
import com.zsy.petshop_01.model.vo.product.InsertVo;
import com.zsy.petshop_01.model.vo.product.UpdateVo;
import com.zsy.petshop_01.service.impl.MinIOService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Component
public class ProductManager {
    @Autowired
    ProductMapper productMapper;
    @Autowired
    MinIOService minIOService;

    public List<Product> selectAll() {
        return productMapper.selectList(null);
    }

    public List<Product> selectByName(String name) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        if (name != null) {
            wrapper.like(Product::getProductName, name);
        }
        return productMapper.selectList(wrapper);
    }

    public void insert(InsertVo insertVo) {
        Product product = new Product();
        BeanUtils.copyProperties(insertVo, product);
        MultipartFile file = insertVo.getFile();
        if (file != null) {
            String minioPath = "";
            try {
                minioPath = minIOService.uploadFile(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
            product.setProductPicture(minioPath);
        }
        productMapper.insert(product);
    }

    public void update(UpdateVo updateVo) {
        Product product = new Product();
        BeanUtils.copyProperties(updateVo, product);
        MultipartFile file = updateVo.getFile();
        if (file != null) {
            String minioPath = "";
            try {
                minioPath = minIOService.uploadFile(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
            product.setProductPicture(minioPath);
        }
        productMapper.updateById(product);
    }

    public void delete(Integer id) {
        productMapper.deleteById(id);
    }
}
